package org.example.controller;

import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.bootstrap.HttpServer;
import org.example.controller.request.SendCodeRequest;
import org.example.enums.BizCodeEnum;
import org.example.enums.SendCodeEnum;
import org.example.service.NotifyService;
import org.example.util.CommonUtil;
import org.example.util.JsonData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: 谢超
 * @date: 2023/07/19 21:57
 **/
@RestController
@RequestMapping("/api/notify/v1")
@Slf4j
public class NotifyController {

    private static final long CAPTCHA_CODE_EXPIRED = 100 * 10 * 60;

    private static String CAPTCHA_PRE_KEY = "account-service:captcha";

    @Resource
    private Producer captchaProducer;

    @Resource
    private NotifyService notifyService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 生成图片验证码接口
     *
     * @param request
     * @param response
     */
    @GetMapping("captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        String captchaText = captchaProducer.createText();
        log.info("验证码内容:{}", captchaText);

        // 存储redis里面，配置过期时间
        // 使用opsForValue设置存储redis的value
        stringRedisTemplate.opsForValue().set(getCaptchaKey(request), captchaText, CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);

        BufferedImage bufferedImage = captchaProducer.createImage(captchaText);

        // try...with...resource
        try (ServletOutputStream outputStream = response.getOutputStream()) {

            ImageIO.write(bufferedImage, "jpg", outputStream);
            outputStream.flush();

        } catch (IOException e) {
            log.error("获取流出错:{}", e.getMessage());
        }
    }

    /**
     * 获取redis验证码key (这里key通过自定义前缀 + 电脑IP和 自定义请求头的MD5算法完成的)
     * @param request
     * @return
     */
    private String getCaptchaKey(HttpServletRequest request) {
        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");

        String key = CAPTCHA_PRE_KEY + CommonUtil.MD5(ip + userAgent);

        log.info("redis验证码key:{}", key);

        return key;
    }


    /**
     * 发送验证码接口
     * @param sendCodeRequest 获取客户端传来的json数据
     * @param request
     * @return
     */
    @PostMapping("send_code")
    public JsonData sendCode(@RequestBody SendCodeRequest sendCodeRequest, HttpServletRequest request) {
        String key = getCaptchaKey(request);
        String redisTempcaptcha = stringRedisTemplate.opsForValue().get(key);
        String captcha = sendCodeRequest.getCaptcha();
        // equalsIgnoreCase方法比较字符串是否相等 (不区分大小写)
        if (redisTempcaptcha != null && captcha != null && redisTempcaptcha.equalsIgnoreCase(captcha)) {
            // 成功
            stringRedisTemplate.delete(key);

            JsonData jsonData = notifyService.sendCode(SendCodeEnum.USE_REGISTER, sendCodeRequest.getTo());
        } else {
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR);
        }
        return JsonData.buildSuccess();
    }
}
